using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;

public class GameUI : MonoBehaviour
{
    [Header("面板引用")]
    public GameObject gamePlayPanel;     // 游戏中UI
    public GameObject waitingPanel;      // 等待开始UI
    public GameObject gameOverPanel;     // 游戏结束UI

    [Header("游戏信息UI")]
    public TextMeshProUGUI timerText;           // 倒计时
    public TextMeshProUGUI teamAScoreText;      // A队分数
    public TextMeshProUGUI teamBScoreText;      // B队分数
    public TextMeshProUGUI playersCountText;    // 玩家数量
    public TextMeshProUGUI winnerText;          // 获胜者信息

    [Header("玩家信息UI")]
    public TextMeshProUGUI playerNameText;      // 玩家名称
    public TextMeshProUGUI playerTeamText;      // 玩家队伍
    public TextMeshProUGUI playerScoreText;     // 玩家得分
    public Slider playerHealthBar;               // 玩家血条

    [Header("复活信息")]
    public GameObject respawnPanel;             // 复活面板
    public TextMeshProUGUI respawnTimerText;    // 复活倒计时

    private GameManager gameManager;
    private NetworkManager networkManager;
    private PlayerController localPlayer;

    void Start()
    {
        // 等待GameManager初始化完成
        StartCoroutine(WaitForGameManager());
    }

    IEnumerator WaitForGameManager()
    {
        while (GameManager.Instance == null)
        {
            yield return null;
        }

        gameManager = GameManager.Instance;
        networkManager = FindObjectOfType<NetworkManager>();

        // 初始化UI状态
        InitializeUI();
    }

    void Update()
    {
        // 查找本地玩家（如果还未找到）
        if (localPlayer == null)
        {
            foreach (var player in FindObjectsOfType<PlayerController>())
            {
                if (player.isLocalPlayer)
                {
                    localPlayer = player;
                    break;
                }
            }
        }

        // 根据游戏状态更新UI
        if (gameManager != null)
        {
            // 游戏进行中
            if (gameManager.gameInProgress)
            {
                gamePlayPanel.SetActive(true);
                waitingPanel.SetActive(false);
                gameOverPanel.SetActive(false);

                // 更新计时器
                UpdateTimer(gameManager.gameTimeRemaining);

                // 更新队伍得分
                UpdateTeamScores(gameManager.teamAScore, gameManager.teamBScore);
            }
            // 等待开始
            else if (!gameOverPanel.activeSelf)
            {
                gamePlayPanel.SetActive(false);
                waitingPanel.SetActive(true);

                // 更新等待玩家数量
                UpdatePlayerCount(FindObjectsOfType<PlayerController>().Length);
            }
        }

        // 更新本地玩家信息UI
        UpdatePlayerUI();

        // 检查玩家死亡状态，显示复活倒计时
        CheckRespawnTimer();
    }

    // 更新游戏计时器
    public void UpdateTimer(float remainingTime)
    {
        if (timerText != null)
        {
            int minutes = Mathf.FloorToInt(remainingTime / 60f);
            int seconds = Mathf.FloorToInt(remainingTime % 60f);
            timerText.text = string.Format("{0:00}:{1:00}", minutes, seconds);
        }
    }

    // 更新队伍分数
    public void UpdateTeamScores(int scoreA, int scoreB)
    {
        if (teamAScoreText != null)
        {
            teamAScoreText.text = scoreA.ToString();
        }

        if (teamBScoreText != null)
        {
            teamBScoreText.text = scoreB.ToString();
        }
    }

    // 更新玩家UI
    private void UpdatePlayerUI()
    {
        if (localPlayer != null)
        {
            // 玩家名称
            if (playerNameText != null)
            {
                playerNameText.text = localPlayer.playerId;
            }

            // 玩家队伍
            if (playerTeamText != null)
            {
                playerTeamText.text = $"Team: {localPlayer.team}";
            }

            // 玩家得分
            if (playerScoreText != null)
            {
                playerScoreText.text = $"Score: {localPlayer.score}";
            }

            // 玩家血条
            if (playerHealthBar != null)
            {
                
                playerHealthBar.value = localPlayer.health / 100f;
            }
        }
    }

    // 检查复活状态
    private void CheckRespawnTimer()
    {
        if (localPlayer != null && localPlayer.isDead)
        {
            // 显示复活面板
            respawnPanel.SetActive(true);

            // 获取复活倒计时
            if (respawnTimerText != null)
            {
                // 从NetworkManager或GameManager获取复活时间
                float remainingTime = gameManager.respawnTime;
                respawnTimerText.text = $"Time to respawn: {Mathf.CeilToInt(remainingTime)}";
            }
        }
        else
        {
            // 隐藏复活面板
            respawnPanel.SetActive(false);
        }
    }

    // 显示游戏结束UI
    public void ShowGameOver(string winningTeam, int scoreA, int scoreB)
    {
        gamePlayPanel.SetActive(false);
        waitingPanel.SetActive(false);
        gameOverPanel.SetActive(true);

        if (winnerText != null)
        {
            if (scoreA == scoreB)
            {
                winnerText.text = "No Win!";
            }
            else
            {
                string teamName = winningTeam == "A" ? "Blue" : "Red";
                winnerText.text = $"{teamName} Win!";
            }
        }
    }

    public void InitializeUI()
    {
        // 设置初始UI状态
        gamePlayPanel.SetActive(false);
        waitingPanel.SetActive(true);
        gameOverPanel.SetActive(false);
        respawnPanel.SetActive(false);
    }

    public void UpdatePlayerCount(int count)
    {
        if (playersCountText != null)
        {
            playersCountText.text = $"Players count: {count}/2";
        }
    }

    public void ShowWaitingPanel()
    {
        waitingPanel.SetActive(true);
        gamePlayPanel.SetActive(false);
        gameOverPanel.SetActive(false);
    }
}